package cn.edu.baiyunu.myapplication.ui.history.components

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SearchBar
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.edu.baiyunu.myapplication.R
import cn.edu.baiyunu.myapplication.ui.history.HistoryViewModel

/**
 * 历史页面顶部栏组件
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HistoryTopBar(
    title: String = "照片历史",
    searchQuery: String,
    isSearchVisible: Boolean,
    sortOrder: HistoryViewModel.SortOrder,
    onSearchQueryChange: (String) -> Unit,
    onSearchClick: () -> Unit,
    onClearClick: () -> Unit,
    onSortOrderSelected: (HistoryViewModel.SortOrder) -> Unit,
    onFilterClick: () -> Unit,
    onDeleteAllClick: () -> Unit,
    onOpenFolderClick: () -> Unit = {},
    modifier: Modifier = Modifier
) {
    var showSortMenu by remember { mutableStateOf(false) }
    
    Column {
        // 顶部工具栏
        TopAppBar(
            title = {
                Text(
                    text = title,
                    fontWeight = FontWeight.SemiBold
                )
            },
            actions = {
                // 打开文件夹按钮
                IconButton(onClick = onOpenFolderClick) {
                    Icon(
                        imageVector = Icons.Default.Folder,
                        contentDescription = "打开图片文件夹"
                    )
                }
                
                // 搜索按钮
                IconButton(onClick = onSearchClick) {
                    Icon(
                        imageVector = Icons.Default.Search,
                        contentDescription = "搜索",
                        tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                    )
                }
                
                // 排序菜单
                Box {
                    IconButton(onClick = { showSortMenu = true }) {
                        Icon(
                            imageVector = Icons.Default.Sort,
                            contentDescription = "排序",
                            tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                        )
                    }
                    
                    DropdownMenu(
                        expanded = showSortMenu,
                        onDismissRequest = { showSortMenu = false }
                    ) {
                        DropdownMenuItem(
                            text = { Text("按时间 - 从新到旧") },
                            onClick = {
                                onSortOrderSelected(HistoryViewModel.SortOrder.DATE_DESC)
                                showSortMenu = false
                            }
                        )
                        DropdownMenuItem(
                            text = { Text("按时间 - 从旧到新") },
                            onClick = {
                                onSortOrderSelected(HistoryViewModel.SortOrder.DATE_ASC)
                                showSortMenu = false
                            }
                        )
                        DropdownMenuItem(
                            text = { Text("按尺寸 - 从大到小") },
                            onClick = {
                                onSortOrderSelected(HistoryViewModel.SortOrder.SIZE_DESC)
                                showSortMenu = false
                            }
                        )
                        DropdownMenuItem(
                            text = { Text("按尺寸 - 从小到大") },
                            onClick = {
                                onSortOrderSelected(HistoryViewModel.SortOrder.SIZE_ASC)
                                showSortMenu = false
                            }
                        )
                    }
                }
                
                // 筛选按钮
                IconButton(onClick = onFilterClick) {
                    Icon(
                        imageVector = Icons.Default.FilterList,
                        contentDescription = "筛选",
                        tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                    )
                }
                
                // 删除全部按钮
                IconButton(onClick = onDeleteAllClick) {
                    Icon(
                        imageVector = Icons.Default.Delete,
                        contentDescription = "删除全部",
                        tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = Color.White
            ),
            modifier = Modifier.shadow(elevation = 4.dp)
        )
        
        // 搜索栏
        AnimatedVisibility(
            visible = isSearchVisible,
            enter = fadeIn() + slideInVertically(),
            exit = fadeOut() + slideOutVertically()
        ) {
            Surface(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                color = Color.White,
                shadowElevation = 4.dp,
                shape = CircleShape
            ) {
                OutlinedTextField(
                    value = searchQuery,
                    onValueChange = onSearchQueryChange,
                    placeholder = { Text("搜索历史照片") },
                    singleLine = true,
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f)
                        )
                    },
                    trailingIcon = {
                        if (searchQuery.isNotEmpty()) {
                            IconButton(onClick = { onSearchQueryChange("") }) {
                                Icon(
                                    imageVector = Icons.Default.Clear,
                                    contentDescription = "清除",
                                    tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f)
                                )
                            }
                        }
                    },
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        focusedBorderColor = Color.Transparent,
                        unfocusedBorderColor = Color.Transparent
                    ),
                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                    keyboardActions = KeyboardActions(onSearch = { onClearClick() }),
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
        
        // 排序和筛选的指示器
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "排序方式:",
                fontSize = 12.sp,
                color = Color(0xFF64748B)
            )
            
            Spacer(modifier = Modifier.width(8.dp))
            
            Text(
                text = when(sortOrder) {
                    HistoryViewModel.SortOrder.DATE_DESC -> "最新优先"
                    HistoryViewModel.SortOrder.DATE_ASC -> "最旧优先"
                    HistoryViewModel.SortOrder.SIZE_DESC -> "尺寸由大到小"
                    HistoryViewModel.SortOrder.SIZE_ASC -> "尺寸由小到大"
                },
                fontSize = 12.sp,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.primary
            )
            
            Icon(
                imageVector = Icons.Default.ArrowDropDown,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(start = 2.dp)
            )
        }
        
        Spacer(modifier = Modifier.height(8.dp))
    }
}

/**
 * 获取排序方式描述
 */
private fun getSortDescription(sortOrder: HistoryViewModel.SortOrder): String {
    return when (sortOrder) {
        HistoryViewModel.SortOrder.DATE_DESC -> "最新优先"
        HistoryViewModel.SortOrder.DATE_ASC -> "最旧优先"
        HistoryViewModel.SortOrder.SIZE_DESC -> "大尺寸优先"
        HistoryViewModel.SortOrder.SIZE_ASC -> "小尺寸优先"
    }
}

/**
 * 历史页面顶部栏组件 - 新版本
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HistoryTopBar(
    title: String,
    isSearchVisible: Boolean,
    searchQuery: String,
    onQueryChange: (String) -> Unit,
    onSearchClick: () -> Unit,
    onClearSearch: () -> Unit,
    onFilterClick: () -> Unit,
    onSortClick: () -> Unit,
    onDeleteAllClick: () -> Unit,
    sortOrder: HistoryViewModel.SortOrder,
    onOpenFolderClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    if (isSearchVisible) {
        SearchBar(
            query = searchQuery,
            onQueryChange = onQueryChange,
            onSearch = { onQueryChange(it) },
            active = true,
            onActiveChange = { if (!it) onClearSearch() },
            leadingIcon = {
                IconButton(onClick = onClearSearch) {
                    Icon(
                        imageVector = Icons.Default.ArrowBack,
                        contentDescription = "返回"
                    )
                }
            },
            trailingIcon = {
                if (searchQuery.isNotEmpty()) {
                    IconButton(onClick = { onQueryChange("") }) {
                        Icon(
                            imageVector = Icons.Default.Clear,
                            contentDescription = "清除搜索"
                        )
                    }
                }
            },
            placeholder = { Text("搜索历史照片...") },
            modifier = Modifier.fillMaxWidth()
        ) {}
    } else {
        TopAppBar(
            title = {
                Text(
                    text = title,
                    fontWeight = FontWeight.Bold
                )
            },
            actions = {
                // 打开文件夹按钮
                IconButton(onClick = onOpenFolderClick) {
                    Icon(
                        imageVector = Icons.Default.Folder,
                        contentDescription = "打开图片文件夹"
                    )
                }
                
                // 搜索按钮
                IconButton(onClick = onSearchClick) {
                    Icon(
                        imageVector = Icons.Default.Search,
                        contentDescription = "搜索"
                    )
                }
                
                // 筛选按钮
                IconButton(onClick = onFilterClick) {
                    Icon(
                        imageVector = Icons.Default.FilterList,
                        contentDescription = "筛选"
                    )
                }
                
                // 排序按钮
                IconButton(onClick = onSortClick) {
                    Icon(
                        imageVector = Icons.Default.Sort,
                        contentDescription = "排序: ${getSortDescription(sortOrder)}"
                    )
                }
                
                // 删除全部按钮
                IconButton(onClick = onDeleteAllClick) {
                    Icon(
                        imageVector = Icons.Default.Delete,
                        contentDescription = "删除全部"
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = Color.White
            ),
            modifier = modifier
        )
    }
} 